package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.domain.User;
import com.example.domain.model.UserLoginDTO;
import com.example.domain.model.UserRegisterDTO;
import com.example.domain.model.UserDTO;
import com.example.service.UserService;
import com.example.shiro.AccountProfile;
import com.example.util.JsonUtil;
import com.example.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Api(tags = "用户管理（用户）")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @RequiresAuthentication
    @ApiOperation(value = "查看用户")
    @GetMapping("/getInfo")
    public R<UserDTO> getInfo(){
        //获取当前用户信息
        AccountProfile account = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

        UserDTO userDTO = JsonUtil.getJsonToBean(userService.getById(account.getId()), UserDTO.class);
        return R.success(userDTO);
    }

    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public R register(@RequestBody UserRegisterDTO userRequest){
        User user = JsonUtil.getJsonToBean(userRequest, User.class);
        return userService.register(user)?R.success():R.error("注册失败，用户名已存在");
    }

    @RequiresAuthentication
    @ApiOperation(value = "更新")
    @PutMapping("/update")
    public R update(@RequestBody UserRegisterDTO userRequest){
        //获取当前用户信息
        AccountProfile account = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

        User user = JsonUtil.getJsonToBean(userRequest,User.class);
        return userService.update(account.getId(),user) ? R.success() : R.error();
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R login(@RequestBody UserLoginDTO userLoginDTO, HttpServletResponse response){
        User user = JsonUtil.getJsonToBean(userLoginDTO, User.class);
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());

        User u = userService.getOne(queryWrapper);

        if (u ==null) {
            return R.error("登录失败，用户名不存在");
        }

        if (!u.getPassword().equals(password)) {
            return R.error("登录失败，密码错误");
        }

        if (!u.getIsActive().equals(1)){
            return R.error("登陆失败，用户已被禁用");
        }

        UserDTO userDTO = JsonUtil.getJsonToBean(u, UserDTO.class);
        String jwt = jwtUtils.generateToken(u.getId(),u.getIsAdmin() == 1);
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return R.success(userDTO);
    }
    @RequiresAuthentication
    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public R logout(){
        SecurityUtils.getSubject().logout();
        return R.success("退出成功");
    }

}
